package com.lottery.shadowbd.io.api;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lottery.shadowbd.bean.LotTrendBean;
import com.lottery.shadowbd.bean.Lottery;
import com.lottery.shadowbd.bean.LotteryHistory;
import com.lottery.shadowbd.bean.TrendData;
import com.lottery.shadowbd.callback.ECallback;
import com.lottery.shadowbd.support.Constant;
import com.lottery.shadowbd.tuple.Tuple2;
import com.lottery.shadowbd.utils.LogUtils;
import com.lottery.shadowbd.utils.LotteryUtils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.FormBody;

/**
 * Created by Administrator on 2018/3/3 0003.
 */

public class LotApiIO {

    volatile static LotApiIO instance;

    LotApiIO() {

    }

    static public LotApiIO getInstance() {
        if (instance == null) {
            synchronized (LotApiIO.class) {
                if (instance == null) {
                    instance = new LotApiIO();
                }
            }
        }
        return instance;
    }

    /**
     * 彩票列表
     *
     * @param rid
     * @param callback
     */
    public void getLotList(String rid, final ECallback<List<Lottery.IEntity>, Tuple2<Integer, String>> callback) {

        FormBody.Builder builder = new FormBody.Builder()
                .add("r", rid);

        MainApiIO.getInstance().postLotRequest(Constant.UrlLotList, builder.build(), new ECallback<String, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(String res) {
                LogUtils.d("彩票列表===onSuccess");
                //JSONObject jsonObject = (JSONObject) res;

                Lottery lotJson = new Gson().fromJson(res, new Lottery().getClass());

                if (callback != null) {
                    if (lotJson != null) {
                        callback.onSuccess(getLotteryList(lotJson));
                    } else {
                        callback.onError(new Tuple2<>(0, "返回信息为空"));
                    }
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                if (callback != null) {
                    callback.onError(error);
                }
            }

            @Override
            public void onThrowable(Throwable e) {
                if (callback != null) {
                    callback.onThrowable(e);
                }
            }
        });
    }

    /**
     * 彩票历史列表
     *
     * @param lotId
     * @param callback
     */
    public void getLotHistory(String lotId, int page, final ECallback<LotteryHistory, Tuple2<Integer, String>> callback) {

        FormBody.Builder builder = new FormBody.Builder()
                .add("lotId", lotId)
                .add("page", String.valueOf(page))
                .add("pageSize", "10");

        MainApiIO.getInstance().postLotRequest(Constant.UrlLotHistoryList, builder.build(), new ECallback<String, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(String res) {
                LogUtils.d("彩票历史列表===onSuccess");
                //JSONObject jsonObject = (JSONObject) res;

                LotteryHistory lotJson = new Gson().fromJson(res, LotteryHistory.class);

                if (callback != null) {
                    if (lotJson != null) {
                        callback.onSuccess(lotJson);
                    } else {
                        callback.onError(new Tuple2<>(0, "返回信息为空"));
                    }
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                if (callback != null) {
                    callback.onError(error);
                }
            }

            @Override
            public void onThrowable(Throwable e) {
                if (callback != null) {
                    callback.onThrowable(e);
                }
            }
        });
    }

    /**
     * 双色球趋势
     *
     * @param callback
     */
    public void getLotTrendList(final ECallback<ArrayList, Tuple2<Integer, InputStream>> callback) {


        MainApiIO.getInstance().postAsnyRequest(Constant.UrlLotTrendList, new ECallback<InputStream, Tuple2<Integer, InputStream>>() {
            @Override
            public void onSuccess(InputStream res) {
                LogUtils.d("双色球趋势===onSuccess");
                //JSONObject jsonObject = (JSONObject) res;

                if (callback != null) {

                    try {
                        callback.onSuccess(setParser(res));
                    } catch (XmlPullParserException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                }
            }

            @Override
            public void onError(Tuple2<Integer, InputStream> error) {
                if (callback != null) {
                    callback.onError(error);
                }
            }

            @Override
            public void onThrowable(Throwable e) {
                if (callback != null) {
                    callback.onThrowable(e);
                }
            }
        });
    }

    /**
     * 大乐透趋势
     *
     * @param callback
     */
    public void getLotDaTrendList(final ECallback<ArrayList, Tuple2<Integer, InputStream>> callback) {


        MainApiIO.getInstance().postAsnyRequest(Constant.UrlLotDaTrendList, new ECallback<InputStream, Tuple2<Integer, InputStream>>() {
            @Override
            public void onSuccess(InputStream res) {
                LogUtils.d("大乐透趋势===onSuccess");
                //JSONObject jsonObject = (JSONObject) res;

                if (callback != null) {

                    try {
                        callback.onSuccess(setParser(res));
                    } catch (XmlPullParserException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                }
            }

            @Override
            public void onError(Tuple2<Integer, InputStream> error) {
                if (callback != null) {
                    callback.onError(error);
                }
            }

            @Override
            public void onThrowable(Throwable e) {
                if (callback != null) {
                    callback.onThrowable(e);
                }
            }
        });
    }


    /**
     * 资讯列表
     *
     * @param rid
     * @param callback
     */
    public void getNewList(String rid, final ECallback<List<Lottery.IEntity>, Tuple2<Integer, String>> callback) {

        FormBody.Builder builder = new FormBody.Builder()
                .add("type", rid)
                .add("id", rid)
                .add("startPage", rid);

        MainApiIO.getInstance().postLotRequest(Constant.UrlNeteastHOST, builder.build(), new ECallback<String, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(String res) {
                LogUtils.d("资讯列表===onSuccess");
                //JSONObject jsonObject = (JSONObject) res;

                Lottery lotJson = new Gson().fromJson(res, new Lottery().getClass());

                if (callback != null) {
                    if (lotJson != null) {
                        callback.onSuccess(getLotteryList(lotJson));
                    } else {
                        callback.onError(new Tuple2<>(0, "返回信息为空"));
                    }
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                if (callback != null) {
                    callback.onError(error);
                }
            }

            @Override
            public void onThrowable(Throwable e) {
                if (callback != null) {
                    callback.onThrowable(e);
                }
            }
        });
    }

    /**
     * @param
     *
     */
    protected ArrayList setParser(InputStream inputStream) throws XmlPullParserException, IOException {
        ArrayList arrayList = new ArrayList();
        Collection arrayList2 = new ArrayList();
        XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
        newPullParser.setInput(inputStream, "utf-8");
        TrendData r0;
        for (int eventType = newPullParser.getEventType(); 1 != eventType; eventType = newPullParser.next()) {
            String name = newPullParser.getName();
            if (eventType == 2) {
                if ("row".equals(name)) {
                    TrendData trendData = new TrendData();
                    trendData.setType("row");
                    String attributeValue = newPullParser.getAttributeValue(null, "pid");
                    if (!(TextUtils.isEmpty(attributeValue) || attributeValue.length() <= 4)) {
                        attributeValue = attributeValue.substring(4);
                    }
                    trendData.setPid(attributeValue);
                    trendData.setRed(newPullParser.getAttributeValue(null, "red"));
                    trendData.setBlue(newPullParser.getAttributeValue(null, "blue"));
                    trendData.setBalls(newPullParser.getAttributeValue(null, "balls"));
                    trendData.setOes(newPullParser.getAttributeValue(null, "oe"));
                    trendData.setBss(newPullParser.getAttributeValue(null, "bs"));
                    trendData.setOne(newPullParser.getAttributeValue(null, "one"));
                    trendData.setTwo(newPullParser.getAttributeValue(null, "two"));
                    trendData.setThree(newPullParser.getAttributeValue(null, "three"));
                    trendData.setCodes(newPullParser.getAttributeValue(null, "codes"));
                    trendData.setSum(newPullParser.getAttributeValue(null, "sum"));
                    trendData.setSpace(newPullParser.getAttributeValue(null, "space"));
                    trendData.setNum(newPullParser.getAttributeValue(null, "num"));
                    trendData.setTimes(newPullParser.getAttributeValue(null, "times"));
                    trendData.setForm(newPullParser.getAttributeValue(null, "form"));
                    arrayList.add(trendData);
                } else if ("dis".equals(name)) {
                    r0 = new TrendData();
                    r0.setType("dis");
                    r0.setRed(newPullParser.getAttributeValue(null, "red"));
                    r0.setBlue(newPullParser.getAttributeValue(null, "blue"));
                    r0.setBalls(newPullParser.getAttributeValue(null, "balls"));
                    r0.setOne(newPullParser.getAttributeValue(null, "one"));
                    r0.setTwo(newPullParser.getAttributeValue(null, "two"));
                    r0.setThree(newPullParser.getAttributeValue(null, "three"));
                    r0.setNum(newPullParser.getAttributeValue(null, "num"));
                    arrayList2.add(r0);
                } else if ("avg".equals(name)) {
                    r0 = new TrendData();
                    r0.setType("avg");
                    r0.setRed(newPullParser.getAttributeValue(null, "red"));
                    r0.setBlue(newPullParser.getAttributeValue(null, "blue"));
                    r0.setBalls(newPullParser.getAttributeValue(null, "balls"));
                    r0.setOne(newPullParser.getAttributeValue(null, "one"));
                    r0.setTwo(newPullParser.getAttributeValue(null, "two"));
                    r0.setThree(newPullParser.getAttributeValue(null, "three"));
                    r0.setNum(newPullParser.getAttributeValue(null, "num"));
                    arrayList2.add(r0);
                } else if ("mmv".equals(name)) {
                    r0 = new TrendData();
                    r0.setType("mmv");
                    r0.setRed(newPullParser.getAttributeValue(null, "red"));
                    r0.setBlue(newPullParser.getAttributeValue(null, "blue"));
                    r0.setBalls(newPullParser.getAttributeValue(null, "balls"));
                    r0.setOne(newPullParser.getAttributeValue(null, "one"));
                    r0.setTwo(newPullParser.getAttributeValue(null, "two"));
                    r0.setThree(newPullParser.getAttributeValue(null, "three"));
                    r0.setNum(newPullParser.getAttributeValue(null, "num"));
                    arrayList2.add(r0);
                } else if ("mlv".equals(name)) {
                    r0 = new TrendData();
                    r0.setType("mlv");
                    r0.setRed(newPullParser.getAttributeValue(null, "red"));
                    r0.setBlue(newPullParser.getAttributeValue(null, "blue"));
                    r0.setBalls(newPullParser.getAttributeValue(null, "balls"));
                    r0.setOne(newPullParser.getAttributeValue(null, "one"));
                    r0.setTwo(newPullParser.getAttributeValue(null, "two"));
                    r0.setThree(newPullParser.getAttributeValue(null, "three"));
                    r0.setNum(newPullParser.getAttributeValue(null, "num"));
                    arrayList2.add(r0);
                }
            }
        }
        arrayList.addAll(arrayList2);

        return arrayList;
    }

    /**
     * @param lottery
     * @return
     */
    private List<Lottery.IEntity> getLotteryList(Lottery lottery) {

        List ret = new ArrayList();
        Map<String, String> available = LotteryUtils.getAllAvailable();
        Set keySet = available.keySet();
        List<Lottery.Entity> entity = lottery.getAllEntities();
        for (Lottery.Entity e : entity) {
            if (e != null && keySet.contains(e.getLotName())) {
                ret.add(e);
            }
        }
        return ret;
    }
}
